package com.mc.fastkit.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResult
import androidx.annotation.CallSuper
import androidx.annotation.LayoutRes
import androidx.core.app.ActivityOptionsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.mc.fastkit.widget.ActivityResultHelper

/**
 * BaseFragment
 * @author: MasterChan
 * @date: 2023-02-25 16:11
 */
abstract class BaseFragment(@LayoutRes private val layout: Int = 0) : Fragment() {

    @get:JvmName("mContext")
    protected lateinit var context: Context

    @get:JvmName("mActivity")
    protected lateinit var activity: FragmentActivity
    protected lateinit var rootView: View
    private val resultHelper = ActivityResultHelper()

    @CallSuper
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        context = requireContext()
        activity = requireActivity()
        resultHelper.register(this)
        return getContentView(inflater, container)?.apply { this@BaseFragment.rootView = this }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        onViewCreated(savedInstanceState)
    }

    abstract fun onViewCreated(savedInstanceState: Bundle?)

    protected open fun getContentView(inflater: LayoutInflater, container: ViewGroup?): View? {
        return inflater.inflate(layout, container, false)
    }

    open fun startActivityForResult(clazz: Class<out Activity>, result: (ActivityResult) -> Unit) {
        resultHelper.launch(clazz, result)
    }

    open fun startActivityForResult(
        intent: Intent,
        options: ActivityOptionsCompat? = null,
        result: (ActivityResult) -> Unit
    ) {
        resultHelper.launch(intent, options, result)
    }
}